package com.jiaai.web.pay;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.jiaai.auth.model.AccessUser;
import com.jiaai.exception.ServerException;
import com.jiaai.filter.aop.TokenIntercept;
import com.jiaai.pay.IPayAPI;
import com.jiaai.pay.IPayTxInterfaceApi;
import com.jiaai.pay.entitiy.PayTxInVO;
import com.jiaai.pay.entitiy.VPay;
import com.jiaai.system.api.IPayManageAPI;
import com.jiaai.system.model.PayManagerVO;
import com.jiaai.util.HttpClientUtil;
import com.jiaai.util.RequestUtils;
import com.jiaai.util.RestResultGenerator;
import comm.utils.pay.alipay.Alipay;
import comm.utils.pay.alipay.entity.AlipayConfigEntity;
import comm.utils.pay.comm.util.Generator;
import comm.utils.pay.comm.util.WeiXinUtil;
import comm.utils.pay.weixin.WeiXinPay;
import comm.utils.pay.weixin.entity.UnifiedOrderEntity;
import comm.utils.pay.weixin.entity.WXPayConfigEntity;
import comm.utils.pay.weixin.entity.WeiXinPayResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * class_name:ZPayController
 * describe:------------------>微信, 支付宝统一下单
 * create_user:张昉平
 * create_date:2018/1/22
 * create_time:16:34
 */
@RestController
@RequestMapping("/api/v1/app/pay")
public class ZPayController {

    @Reference
    private IPayAPI payAPI;
    @Reference
    private IPayManageAPI payManageAPI;
    @Reference
    private IPayTxInterfaceApi interfaceApi;

    /*
     * application配置里, 配置异步通知的地址, 切记
     */
    @Value("${pay.wxNotifyUrl}")
    private String wxNotifyUrl;
    @Value("${pay.alipayNotifyUrl}")
    private String alipayNotifyUrl;

    /**
     * 获取支付签名
     * type 1:微信 2:支付宝
     * @param payManagerId
     * @param type
     * @param body
     * @param subject
     * @return
     */
    @PostMapping("/pay")
    @TokenIntercept(checkVisitor = true)
    public Object sign(@RequestParam Integer payManagerId
            , @RequestParam Integer type
            , @RequestParam String body
            , @RequestParam String subject
            , HttpServletRequest request){
        AccessUser user = RequestUtils.getUser();
        //充值档次
        PayManagerVO payManager = payManageAPI.getOne(payManagerId);
        //支付接口参数
        PayTxInVO inVO = interfaceApi.getOne(type);

        if (inVO == null) return RestResultGenerator.genErrorResult("支付失败, 没有配置");

        if (inVO.getType() == 1){//微信
            return getWXSign(body, request, user, payManager, inVO);
        }else if (inVO.getType() == 2){//支付宝
            return getAlipaySign(body, subject, user, payManager, inVO);

        }

        return RestResultGenerator.genErrorResult("大爷的,就是支付不了");
    }

    private Object getAlipaySign(String body, String subject, AccessUser user, PayManagerVO payManager, PayTxInVO inVO) {
    /*
        ==================================================================支付宝
     */
        //订单
        String orderNo = Generator.alipayOrderNo();
        AlipayConfigEntity entity = JSONObject.parseObject(inVO.getPiConfig(), AlipayConfigEntity.class);
        entity.setBody(body);
        entity.setSubject(subject);
        entity.setAlipay_notify_url(alipayNotifyUrl);
        //创建订单
        VPay vPay = new VPay();
        vPay.setInterfaceId(inVO.getPiId());
        vPay.setOutTradeNo(orderNo);
        vPay.setGold(payManager.getGold());
        vPay.setOldGold(payManager.getGold());
        vPay.setPriceUnit("RMB");
        vPay.setChannel(2);//支付宝
        vPay.setmId(user.getUserId());
        vPay.setPrice(new BigDecimal(payManager.getRmb()));
        vPay.setVerifyId(entity.app_id);
        vPay.setVerifySecret(entity.getPublic_key());
        try {
            vPay = payAPI.createPayOrder(vPay);
        } catch (ServerException e) {
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("大爷的,就是支付不了");
        }
        //生成sdk签名, 不会访问支付宝接口
        String sign = Alipay.readyToPay(payManager.getRmb().toString(), orderNo, entity);
        return RestResultGenerator.genSuccessResult(sign);
    }

    private Object getWXSign(String body, HttpServletRequest request, AccessUser user, PayManagerVO payManager, PayTxInVO inVO) {
    /*
        ==================================================================微信
     */
        String orderNo = Generator.weixinOrderNo();
        WXPayConfigEntity configEntity = JSONObject.parseObject(
                JSONObject.parseObject(inVO.getPiConfig()).getString("app")
                , WXPayConfigEntity.class);
        //创建订单
        VPay vPay = new VPay();
        vPay.setInterfaceId(inVO.getPiId());
        vPay.setOutTradeNo(orderNo);
        vPay.setGold(payManager.getGold());
        vPay.setOldGold(payManager.getGold());
        vPay.setPriceUnit("RMB");
        vPay.setChannel(1);//微信
        vPay.setmId(user.getUserId());
        vPay.setPrice(new BigDecimal(payManager.getRmb()));
        vPay.setVerifyId(configEntity.getAppid());
        vPay.setVerifySecret(configEntity.getSrete_key());
        try {
            vPay = payAPI.createPayOrder(vPay);
        } catch (ServerException e) {
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("大爷的,就是支付不了");
        }

        UnifiedOrderEntity entity = new UnifiedOrderEntity();
        entity.setAttach("{}");
        entity.setBody(body);
        entity.setNotify_url(wxNotifyUrl);
        entity.setOut_trade_no(orderNo);
        entity.setSpbill_create_ip(HttpClientUtil.getIpAddress(request));
        entity.setTotal_fee((payManager.getRmb() * 100) +"");

        entity.setMch_id(configEntity.getMch_id());
        entity.setAppid(configEntity.getAppid());

        //访问微信接口
        String res = WeiXinPay.unifiedOrder(entity, configEntity);
        WeiXinPayResult result = WeiXinUtil.xml2Result(res);

        if (result.getCode() == 500){
            return RestResultGenerator.genErrorResult(result.getDesc());
        }

        return RestResultGenerator.genSuccessResult(result);
    }

    @GetMapping("/myPayOrder")
    @TokenIntercept
    public Object myTxOrder(Integer curr) throws Exception {
        AccessUser accessUser= RequestUtils.getUser();
        return RestResultGenerator.genSuccessResult(payAPI.myPayOrder(curr,accessUser.getUserId()));
    }
}
